const fs = require("fs"),
  xml2js = require("xml2js");

const DIR = __dirname + "/..";

function tsxContent(name, viewBox, paths) {
  let pathsStr = `['${paths.join("','")}']`;

  return `/** 生成文件，请勿修改 */
import * as React from 'react'
import Icon from '../icon'
import type { CSSProperties } from 'react'

function ${name} ({ className, style }: { className?: string, style?: CSSProperties }) {
    return <Icon className={className} style={style} viewBox="${viewBox}" paths={${pathsStr}} />
}
${name}.displayName = ${name}
export default ${name}
`;
}

async function generateComponent(name, filename) {
  let source = fs.readFileSync(DIR + "/src/svg/" + filename);

  const xmlObject = await new Promise(function (resolve, reject) {
    xml2js.Parser().parseString(source, (err, result) => {
      if (err) reject(err);
      if (result) resolve(result);
    });
  });

  let compact = (d) =>
    d.replace(/(\d+\.\d+)/g, (s) => Math.round(parseFloat(s) * 100) / 100);

  const paths = xmlObject.svg.path

  const pathFill = paths.reduce((pre, next) => {
    if (next.$.fill) {
      pre.push(next.$.fill)
    }
    return pre
  }, [])

  const isSameFill = pathFill.length === 0 || pathFill.every((p) => p === pathFill[0])

  fs.writeFileSync(
    `${DIR}/src/icons/${name}.tsx`,
    tsxContent(
      name,
      xmlObject.svg.$.viewBox,
      xmlObject.svg.path.map((i) => {
       const fillProps = isSameFill ? {} : i.$.fill ? { fill: i.$.fill} : {}
       return JSON.stringify({
         d: compact(i.$.d),
         ...fillProps
       })
      })
    )
  );
}

function generateIndex(names) {
  let content = names.reduce(
    (r, i) => `${r}export { default as ${i} } from "./${i}"\n`,
    "/** 生成文件，请勿修改 */\n"
  );
  fs.writeFileSync(DIR + `/src/icons/index.tsx`, content);
}

function formatName(name) {
  // if (name[0] == "-") name = name.slice(1);
  let camelName = name
    .slice(0, name.indexOf("."))
    .split("-")
    .filter((i) => i)
    .map((i) => i[0].toUpperCase() + i.slice(1))
    .join("");

  // filename[0].toUpperCase() + filename.slice(1, filename.indexOf("."));

  return camelName;
}

async function run() {
  let fnames = fs.readdirSync(DIR + "/src/svg");

  // 删除旧文件并创建空目录
  fs.rmdirSync(DIR + "/src/icons", { recursive: true });
  fs.mkdirSync(DIR + "/src/icons");
  // 删除原有生成文件
  fs.rmdirSync(DIR + "/dist", { recursive: true });

  let names = [];
  for (let filename of fnames) {
    let name = formatName(filename);
    generateComponent(name, filename);
    names.push(name);
  }
  generateIndex(names);
}

run();
